package com.mainbo.core.activemq.parser;

import com.alibaba.fastjson.JSON;
import com.mainbo.core.activemq.model.PfMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;

/**
 * @author moshang
 * @date 2020-03-01
 **/
public class JsonMessageParser<T> implements MessageParser<T>, Marshaller<T> {

    private static final Logger logger = LoggerFactory
            .getLogger(JsonMessageParser.class);

    private Class<T> c;

    public JsonMessageParser(Class<T> c) {
        this.c = c;
    }

    @Override
    public String marshall(PfMessage<Serializable> input) throws MessageParseException {
        return JSON.toJSONString(input);
    }

    @Override
    public T parse(String message) throws MessageParseException {
        assert (message != null);
        try {
            return JSON.parseObject(message, c);
        } catch (Exception e) {
            logger.error("parse json failed ", e);
        }
        return null;
    }

}